<template>
    <BasicModal @register="registerModal" :footer="false">
        <div style="text-align:center">
            <div class="test">
                <canvas ref="qrcodeCanvas" id="test" width="400" height="380"></canvas>
            </div>
            <a-button type="primary" class="mt-5" @click="imagePrint">打印</a-button>
        </div>
    </BasicModal>
</template>
<script lang="ts">
import QRcode from "qrcode";
import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
import { defineComponent, ref, unref, onMounted } from 'vue';
import { QrCode, QrCodeActionType } from '/@/components/Qrcode/index';
import LogoImg from '/@/assets/images/logo.png';
import { CollapseContainer } from '/@/components/Container/index';
// import { PageWrapper } from '/@/components/Page';
import printJS from 'print-js';



export default defineComponent({

    components: { CollapseContainer, QrCode, BasicModal },//PageWrapper,
    setup() {
        // 打印
        const btFn = () => {
            //将canvas生成的二维码，转为base64
            const imageData = document.querySelector('#test').toDataURL('image/png')
            // Blob 下载
            base64Down('测试', imageData)

        }
        const base64Down = (fileName, base64URL) => {
            const a = document.createElement('a')
            // 将 a 标签的 download 属性设置为要下载的文件名
            a.download = fileName || 'image'
            // 创建 Blob 对象，并获取 base64 数据的 MIME 类型
            const mimeType = base64URL.match(/:(.*?);/)[1]
            // 将 base64 数据转换为字节数组
            const byteCharacters = atob(base64URL.split(',')[1])
            const byteNumbers = new Array(byteCharacters.length)
            // 将字节数组填充到 Uint8Array 中
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i)
            }
            const byteArray = new Uint8Array(byteNumbers)
            // 创建 Blob 对象
            const blob = new Blob([byteArray], { type: mimeType })
            // 将 Blob 对象的 URL 赋值给 a 标签的 href 属性
            a.href = URL.createObjectURL(blob)
            // 将a标签暂时添加到 body 中，触发下载
            document.body.appendChild(a)
            a.click()
            // 下载完成后，将 a 标签从 body 中移除
            document.body.removeChild(a)
        }


        const qrCodeUrl = ref<string>();
        const [registerModal] = useModalInner((record: any) => {
            updateQRCode('samId:' + record.id + ';' + 'samName:' + record.samName + ';' +
                'samNum:' + record.samNum + ';' + 'samModel:' + record.model + ';'+'samDate:'+record.samDate, record.samName, record.samNum, record.samDate);
        });


        const qrDiyRef = ref<Nullable<QrCodeActionType>>(null);

        function downloadDiy() {
            const qrEl = unref(qrDiyRef);
            if (!qrEl) return;
            qrEl.download('Qrcode');
        }

        // function onQrcodeDone({ ctx }: any) {
        //     if (ctx instanceof CanvasRenderingContext2D) {
        //         // 额外绘制
        //         ctx.fillStyle = 'black';
        //         ctx.font = '15px "微软雅黑"';
        //         ctx.textBaseline = 'top';
        //         ctx.textAlign = 'right';
        //         ctx.fillText('设备名称:' + registerModal.arguments, 100, 195, 200);
        //     }
        // }




        //打印二维码
        function imagePrint() {
            //将canvas生成的二维码，转为base64
            const imageData = document.querySelector('#test').toDataURL('image/png');          
       
            const imageUrl = base64ToImageUrl(imageData);
  
            printJS({
                printable: [imageUrl],
                type: 'image',
                header: 'Multiple Images',
                imageStyle: 'width:100%;',
            });
        }
        // console.log("mess3" + qrCodeUrl);

        function base64ToImageUrl(base64Data) {
            // console.log('base64:'+base64Data);
            
            const blob = dataURItoBlob(base64Data);
            return URL.createObjectURL(blob);
        }

        function dataURItoBlob(dataURI) {
            // console.log('dataurl'+dataURI);
            
            const byteString = atob(dataURI.split(',')[1]);
            const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
            const arrayBuffer = new ArrayBuffer(byteString.length);
            const uint8Array = new Uint8Array(arrayBuffer);

            for (let i = 0; i < byteString.length; i++) {
                uint8Array[i] = byteString.charCodeAt(i);
            }

            return new Blob([arrayBuffer], { type: mimeString });
        }


        // 函数来生成二维码
        const updateQRCode = async (content, value1, value2, value3) => {

            const canvas: any = document.querySelector('#test');
            
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // 设置背景颜色
            ctx.fillStyle = 'white';
            ctx.fillRect(800, 90, 250, 300);
            // 绘制文字
            ctx.fillStyle = 'black'; // 设置文字颜色为黑色
            ctx.font = '14px 微软雅黑';
            ctx.fillText('样品名称:' + value1, 150, 85);
            ctx.fillText('样品编号:' + value2, 150, 105);
            ctx.fillText('入库时间:' + value3, 150, 125);
            // ctx.fillText('国别:' + value4, 150, 145);

            // 绘制二维码
            const qrCodeData = await QRcode.toDataURL(content, {
                width: 250,
                height: 180
            });
            const qrCodeImage = new Image();
            qrCodeImage.src = qrCodeData;
            qrCodeImage.onload = () => {
                ctx.drawImage(qrCodeImage, 130, 128); // 调整二维码的位置
                // ctx.drawImage(qrCodeImage, 130, 108); // 调整二维码的位置
            };

        };


        return {
            // onQrcodeDone,
            qrCodeUrl,
            LogoImg,
            downloadDiy,
            qrDiyRef,
            registerModal,
            imagePrint,
            // fn,
            btFn,
            base64Down

        };
    },
});

</script>
<style scoped>
.qrcode-demo-item {
    width: 30%;
    margin-right: 1%;
}
</style>
  